<!-- 新闻详情页面 -->

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { View } from '@element-plus/icons-vue'
import service from '@/utils/axios';
import { ApiResponse, stringToApiResponse } from '@/types/apiResponse';
import type { News } from '@/types/news';
import type { Comments, Comment, Reply } from '@/types/comment';
import type { OperationState } from '@/types/operation';
import { useLoginStore } from '@/stores/useLoginStore';
import { useUserStore } from '@/stores/useUserStore';

const route = useRoute()
const router = useRouter()
const loginStore = useLoginStore()
const userStore = useUserStore()

// 使用route.params获取参数中的新闻id
const newsId = Number(route.params.id);

// 文章数据初始化
const article = ref<News>({
  id: Number(route.params.id),
  title: '',
  author: '',
  authorAvatar: '',
  authorDesc: '',
  publishTime: '',
  readCount: 0,
  content: '',
  tags: [],
  likes: 0,
  dislikes: 0,
  favorites: 0,
  authorStats: {
    authorId: 0,
    articles: 0,
    followers: 0,
    likes: 0,
    followedIf: false
  }
})

// 评论列表初始化
const comments = ref<Comments>({
  commentNum: 0,
  commentList: [
    {
      id: 0,
      userId: 0,
      author: '',
      avatar: '',
      content: '',
      time: '',
      likes: 0,
      supportIf: 0,
      childCommentNum: 0,
      replies: [
        {
          id: 0,
          userId: 0,
          author: '',
          avatar: '',
          repliedUser: '',
          content: '',
          time: '',
          likes: 0,
          supportIf: 0
        }
      ]
    }
  ]
})

// 定义操作标识并初始化
const operationState = ref<OperationState>({
  newsSupportIf: 0,
  newsOppositionIf: 0,
  newsCollectionIf: 0
})

const commentsKey = ref(0);

// 分页器 更改页码时触发
const handleCurrentChange = async (val: number) => {
  console.log(`current page: ${val}`)
  currentPage.value = val;
  commentsRender(await loadNewsComments(newsId));
}

// 分页器 切换每页显示条数时触发
const handleSizeChange = async (val: number) => {
  console.log(`${val} items per page`)
  pageSize.value = val;
  commentsRender(await loadNewsComments(newsId));
}

// 分页器 当前页码
const currentPage = ref(1);
// 分页器 每页显示条数
const pageSize = ref(10);

// 当前排序类型 0: 默认 1: 按热度 2: 按时间
const sortType = ref(0);


onMounted(async () => {
  window.scrollTo(0, 0); // 页面加载完成后滚动到顶部

  // 加载访客用户基础信息
  userStore.loadUserInfo();
  // console.log(userStore.userInfo);

  // 调用加载新闻详情方法
  const newsResponse = await loadNewsDetail(newsId);
  if (newsResponse.code === 200) {
    const data = JSON.parse(JSON.stringify(newsResponse.data));
    // 将响应体中的数据，按照接口文档的响应体结构，进行解封装
    const newsInfo = data.newsBody.newsInfo;
    const issues = data.issue;
    const authorInfo = data.newsBody.authorInfo;

    // 将解封装后的数据赋值给用于渲染页面的变量
    // 以下是新闻和作者信息的数据
    article.value.id = newsInfo.id;
    article.value.title = newsInfo.title;
    article.value.author = authorInfo.nickname;
    article.value.authorAvatar = authorInfo.profile;
    article.value.authorDesc = authorInfo.introduction;
    article.value.publishTime = newsInfo.publishTime;
    article.value.readCount = newsInfo.pageView;
    article.value.content = newsInfo.content;
    article.value.tags = issues;
    article.value.likes = newsInfo.supportNum;
    article.value.dislikes = newsInfo.oppositionNum;
    article.value.favorites = newsInfo.collectionNum;
    article.value.authorStats.authorId = authorInfo.authorId;
    article.value.authorStats.articles = authorInfo.newsNum;
    article.value.authorStats.followers = authorInfo.followerNum;
    article.value.authorStats.likes = authorInfo.supportedNum;
    article.value.authorStats.followedIf = authorInfo.followedIf;

    if (data.operation) {
      const operation = data.operation;
      // 这里可以看出来其实是可以直接对Object赋值的，以后有时间可以把获取新闻详情的响应结构统一一下直接赋值

      // 以下是操作标识的数据
      operationState.value.newsSupportIf = operation.newsSupportIf;
      operationState.value.newsOppositionIf = operation.newsOppositionIf;
      operationState.value.newsCollectionIf = operation.newsCollectionIf;
    } else {
      // 未登录状态下，默认操作标识为0
      operationState.value.newsSupportIf = 0;
      operationState.value.newsOppositionIf = 0;
      operationState.value.newsCollectionIf = 0;
    }
  } else {
    console.log('获取新闻详情失败');
    router.push('/404');
  }

  // 调用加载评论列表方法
  const commentsResponse = await loadNewsComments(newsId);
  commentsRender(commentsResponse);

})

// 加载新闻详细信息
const loadNewsDetail = async (newsId: number): Promise<ApiResponse<string>> => {

  const response = await service.get<string>('/news/getDetail', {
    params: {
      newsId: newsId
    }
  });

  return stringToApiResponse(response.data);
}

// 将加载出来的评论数据渲染到页面上
const commentsRender = (commentsResponse: ApiResponse<string>) => {
  if (commentsResponse.code === 200) {
    comments.value.commentNum = 0;
    comments.value.commentList = [];

    const data = JSON.parse(JSON.stringify(commentsResponse.data));

    comments.value.commentNum = data.commentNum;
    // 全部评论内容
    const newsComments: Array<any> = Object.values(data.newsComments);

    // 对于评论列表中的每一条评论comment
    newsComments.forEach((comment: any) => {

      // 定义一个临时的评论类，用于将后端响应数据传给前端
      const commentFront: Comment = ({
        id: 0, userId: 0, author: '', avatar: '', content: '', time: '', likes: 0, supportIf: 0, replies: [], childCommentNum: 0
      });
      commentFront.id = comment.id;
      commentFront.userId = comment.userId;
      commentFront.author = comment.nickname;
      commentFront.avatar = comment.profile;
      commentFront.content = comment.comment;
      commentFront.time = comment.commitTime;
      commentFront.likes = comment.supportNum;
      // 若为已登录请求
      if (data.isLogin === 1) {
        commentFront.supportIf = comment.supportIf;
      }

      // 处理子评论
      const newsChildComments: Array<any> = Object.values(comment.childComments);
      commentFront.childCommentNum = newsChildComments.length;

      // 对于每一条子评论childComment
      newsChildComments.forEach((childComment: any) => {

        // 定义一个临时的子评论类
        const childCommentFront: Reply = ({
          id: 0, userId: 0, author: '', avatar: '', repliedUser: '', content: '', time: '', likes: 0, supportIf: 0
        });
        childCommentFront.id = childComment.id;
        childCommentFront.userId = childComment.userId;
        childCommentFront.author = childComment.nickname;
        childCommentFront.avatar = childComment.profile;
        childCommentFront.repliedUser = childComment.repliedNickname;
        childCommentFront.content = childComment.comment;
        childCommentFront.time = childComment.commitTime;
        childCommentFront.likes = childComment.supportNum;
        // 若为已登录请求
        if (data.isLogin === 1) {
          childCommentFront.supportIf = childComment.supportIf;
        }
        commentFront.replies.push(childCommentFront);
      })
      comments.value.commentList.push(commentFront);
    })

  } else {
    console.log('暂无评论');
    // 若没有评论，则清空评论列表
    comments.value.commentNum = 0;
    comments.value.commentList = [];
  };
}

// 加载新闻全部评论
const loadNewsComments = async (newsId: number): Promise<ApiResponse<string>> => {
  console.log("load all comments, newsId: ", newsId);

  const response = await service.get<string>('/comment/getNewsComments', {
    params: {
      newsId: newsId,
      page: currentPage.value,
      pageSize: pageSize.value,
      sortType: sortType.value
    }
  });

  return stringToApiResponse(response.data);
}

// 排序方法，接受一个参数作为排序方法，0: 默认 1: 按时间 2: 按热度
const commentSort = async (type: number) => {
  if (type === 0) {
    doPrompt('按默认排序')
  } else if (type === 1) {
    doPrompt('按时间排序')
  } else if (type === 2) {
    doPrompt('按热度排序')
  }
  sortType.value = type;

  const commentsResponse = await loadNewsComments(newsId);
  commentsRender(commentsResponse);
}

// 提示信息
const doPrompt = (message: string) => {
  ElMessage.warning({
    message: message,
    appendTo: '#top-nav'
  })
}

// 相关推荐
const relatedArticles = ref([
  {
    id: 1,
    title: 'AI在医疗领域的最新应用',
    image: 'https://picsum.photos/200/150?random=1',
    readCount: '8.2万'
  },
  {
    id: 2,
    title: '未来十年AI发展趋势预测',
    image: 'https://picsum.photos/200/150?random=2',
    readCount: '6.5万'
  }
])

// 互动功能接口，接受一个操作类型参数
const interactionOperate = async (opType: number, newsId: number) => {
  const response = await service.get<string>('/news/operateNews', {
    params: {
      newsId: newsId,
      opType: opType
    }

  });
  return stringToApiResponse(response.data);
}

// 点赞功能
const handleLike = async () => {
  // 先发起请求，这样才能根据请求结果决定是否更新页面数据
  const apiResponse = await interactionOperate(1, newsId);

  if (apiResponse.code === 200) {
    doPrompt(apiResponse.data);

    if (operationState.value.newsSupportIf === 0) {
      // 点赞操作

      // 点赞操作标识取反
      operationState.value.newsSupportIf = operationState.value.newsSupportIf === 0 ? 1 : 0;
      article.value.likes = article.value.likes + 1;
      if (operationState.value.newsOppositionIf === 1) {
        // 如果之前是点踩的状态，则将点踩数减一并清空点踩标识
        article.value.dislikes = article.value.dislikes - 1;
        operationState.value.newsOppositionIf = 0;
      }
    } else {
      // 取消点赞操作

      // 点赞操作标识取反
      operationState.value.newsSupportIf = operationState.value.newsSupportIf === 0 ? 1 : 0;
      article.value.likes = article.value.likes - 1;

    }

  } else if (apiResponse.code === 401) {
    doPrompt('请先登录');
    loginStore.openLoginDialog();
  } else {
    doPrompt('点赞失败');
  }

}

// 点踩功能
const handleDislike = async () => {

  const apiResponse = await interactionOperate(2, newsId);

  if (apiResponse.code === 200) {
    doPrompt(apiResponse.data);

    if (operationState.value.newsOppositionIf === 0) {
      // 点踩操作

      // 点踩操作标识取反
      operationState.value.newsOppositionIf = operationState.value.newsOppositionIf === 0 ? 1 : 0;
      article.value.dislikes = article.value.dislikes + 1;
      if (operationState.value.newsSupportIf === 1) {
        // 如果之前是点赞的状态，则将点赞数减一并清空点赞标识
        article.value.likes = article.value.likes - 1;
        operationState.value.newsSupportIf = 0;
      }
    } else {
      // 取消点踩操作

      // 点踩操作标识取反
      operationState.value.newsOppositionIf = operationState.value.newsOppositionIf === 0 ? 1 : 0;
      article.value.dislikes = article.value.dislikes - 1;

    }

  } else if (apiResponse.code === 401) {
    doPrompt('请先登录');
    loginStore.openLoginDialog();
  } else {
    doPrompt('点赞失败');
  }
}

// 收藏功能
const handleFavorite = async () => {

  const apiResponse = await interactionOperate(3, newsId);

  if (apiResponse.code === 200) {
    doPrompt(apiResponse.data);
    // 收藏操作标识取反
    operationState.value.newsCollectionIf = operationState.value.newsCollectionIf === 0 ? 1 : 0;
    article.value.favorites = operationState.value.newsCollectionIf === 0 ? article.value.favorites - 1 : article.value.favorites + 1;

  } else if (apiResponse.code === 401) {
    doPrompt('请先登录');
    loginStore.openLoginDialog();
  } else {
    doPrompt('收藏失败');
  }

}

const handleShare = () => {
  console.log('分享')
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 关注功能接口, 接收作者ID作参数
const userFollow = async (userId: number) => {
  const response = await service.get<string>('/user/follow', {
    params: {
      followedUserId: userId
    }
  });
  return stringToApiResponse(response.data);
}

// 关注作者功能
const handleAuthorFollow = async (authorId: number) => {

  const apiResponse = await userFollow(authorId);

  if (apiResponse.code === 200) {
    doPrompt(apiResponse.data);
    // 关注操作标识取反
    article.value.authorStats.followedIf = !article.value.authorStats.followedIf;
  } else if (apiResponse.code === 400) {
    doPrompt(apiResponse.data);
  } else if (apiResponse.code === 401) {
    doPrompt('请先登录');
    loginStore.openLoginDialog();
  }
}

// 点击“评论”图标按钮，滚动到评论区的方法
const handleComment = () => {

  const commentSection = document.getElementById('comment-box');
  if (commentSection) {
    // 获取锚点位置的坐标
    const offset = 150; // 向下偏移的像素值
    const elementPosition = commentSection.getBoundingClientRect().top; // 获取锚点相对于视口的位置
    const offsetPosition = elementPosition + window.scrollY - offset; // 计算最终滚动的位置

    // 平滑滚动到目标位置
    window.scrollTo({
      top: offsetPosition,
      behavior: 'smooth'
    });
  }

}

// 评论输入框和二级评论输入框的内容
const commentContentGlobal = ref('')
const childCommentContentGlobal = ref('')

// 发表评论功能接口
const commentCommit = async (parentId: number, repliedUserId: number, comment: string) => {
  const response = await service.post<string>('/comment/commit', {
    "newsId": newsId,
    "parentId": parentId === 0 ? null : parentId,
    "repliedUserId": repliedUserId === 0 ? null : repliedUserId,
    "comment": comment,
    "userId": userStore.userInfo.id
  });

  return stringToApiResponse(response.data);
}

// 发表评论
const submitComment = async (commentId: number, repliedUserId: number, repliedUser: string, commentContent: string) => {
  if (!commentContent.trim()) {
    doPrompt('评论内容不能为空');
    return
  }

  if (commentId === 0 && repliedUserId === 0) {
    // 发布一级评论
    // 先发起请求，这样才能根据请求结果决定是否更新页面数据
    const apiResponse = await commentCommit(0, 0, commentContent);

    if (apiResponse.code === 200) {
      doPrompt('发表评论成功');
      // 在页面上显示刚刚发表的评论
      comments.value.commentList.unshift({
        // 在这里传入UserStore中的用户信息
        id: apiResponse.data,
        userId: userStore.userInfo.id,
        author: userStore.userInfo.nickname,
        avatar: userStore.userInfo.avatar,
        content: commentContent,
        time: '刚刚',
        likes: 0,
        supportIf: 0,
        replies: [],
        childCommentNum: 0
      })

      comments.value.commentNum = comments.value.commentNum + 1;
      blurHandler();

      commentContentGlobal.value = '';
    } else if (apiResponse.code === 401) {
      doPrompt('请先登录');
      loginStore.openLoginDialog();
    }

  } else {
    // 发布二级评论
    const apiResponse = await commentCommit(commentId, repliedUserId, commentContent);
    if (apiResponse.code === 200) {

      doPrompt('回复成功');
      // 在页面上显示刚刚发表的评论

      comments.value.commentList.find(comment => comment.id === commentId)?.replies.unshift({
        id: apiResponse.data,
        userId: userStore.userInfo.id,
        author: userStore.userInfo.nickname,
        avatar: userStore.userInfo.avatar,
        repliedUser: repliedUser,
        content: commentContent,
        time: '刚刚',
        likes: 0,
        supportIf: 0
      })

      blurHandler();

      childCommentContentGlobal.value = '';
    } else if (apiResponse.code === 401) {
      doPrompt('请先登录');
      loginStore.openLoginDialog();
    }
  }
}

// 用于定位被回复评论和子评论的输入框
const replyCommentId = ref(-1);
const replyChildCommentId = ref(-1);

// 对评论回复，定位输入框的位置
const replyComment = async (commentId: number) => {
  replyChildCommentId.value = 0;
  replyCommentId.value = commentId;
}

// 发表子评论，定位输入框的位置
const replyChildComment = async (commentId: number, replyId: number) => {
  replyChildCommentId.value = replyId;
  replyCommentId.value = commentId;
}

// 重置发评论输入框的定位，也就是取消全部地方的输入框
const blurHandler = () => {
  replyCommentId.value = -1;
  replyChildCommentId.value = -1;
}

// 评论点赞功能接口，接收评论ID和子评论ID作参数（实际业务只能有其中一个参数，因此有一个一定为空值）
const commentSupport = async (commentId: number, replyId: number) => {
  const response = await service.get<string>('/comment/support', {
    params: {
      commentId: commentId === 0 ? null : commentId,
      childCommentId: replyId === 0 ? null : replyId
    }
  });
  return stringToApiResponse(response.data);
}

// 点赞评论
const likeComment = async (comment: Comment) => {
  console.log(comment.id);
  // 先发起请求，这样才能根据请求结果决定是否更新页面数据
  const apiResponse = await commentSupport(comment.id, 0);
  if (apiResponse.code === 200) {
    doPrompt(apiResponse.data);

    // 点赞操作标识取反
    comment.supportIf = comment.supportIf === 0 ? 1 : 0;
    // 下面的语句是 更新了评论是否点赞的值后再执行的，因此相当于在问，用户点赞完毕之后，该评论的点赞数有什么变化。
    comment.likes = comment.supportIf === 0 ? comment.likes - 1 : comment.likes + 1;
  } else if (apiResponse.code === 401) {
    doPrompt('请先登录');
    loginStore.openLoginDialog();
  }
}

// 点赞子评论
const likeChildComment = async (reply: Reply) => {
  console.log(reply.id);

  const apiResponse = await commentSupport(0, reply.id);
  if (apiResponse.code === 200) {
    doPrompt(apiResponse.data);

    // 点赞操作标识取反
    reply.supportIf = reply.supportIf === 0 ? 1 : 0;
    reply.likes = reply.supportIf === 0 ? reply.likes - 1 : reply.likes + 1;
  } else if (apiResponse.code === 401) {
    doPrompt('请先登录');
    loginStore.openLoginDialog();
  }
}

// 访问其个人信息
const handleUserProfile = (authorId: number) => {
  router.push({
    path: `/user/profile/${authorId}`,
  })
}
</script>

<template>
  <div class="max-w-6xl mx-auto px-4 py-8">
    <!-- 返回按钮 -->
    <div class="mb-6">
      <el-button class="!px-3" @click="goBack">
        <el-icon>
          <ArrowLeft />
        </el-icon>
        返回
      </el-button>
    </div>

    <el-backtop :right="100" :bottom="100" />

    <div class="flex gap-8">
      <!-- 左侧互动工具栏 -->
      <div class="w-16">
        <div class="sticky top-24 space-y-6">
          <div v-for="(item, index) in [
            {
              icon: operationState.newsSupportIf ? 'fa fa-thumbs-up fa-2x' : 'fa fa-thumbs-o-up fa-2x',
              label: '点赞',
              value: (article.likes == 0) ? '0' : article.likes,
              handler: handleLike
            },
            {
              icon: operationState.newsOppositionIf ? 'fa fa-thumbs-down fa-2x' : 'fa fa-thumbs-o-down fa-2x',
              label: '点踩',
              value: (article.dislikes == 0) ? '0' : article.dislikes,
              handler: handleDislike
            },
            {
              icon: 'fa fa-comment-o fa-2x',
              label: '评论',
              value: (comments.commentNum == 0) ? '0' : comments.commentNum,
              handler: handleComment
            },
            {
              icon: operationState.newsCollectionIf ? 'fa fa-star fa-2x' : 'fa fa-star-o fa-2x',
              label: '收藏',
              value: (article.favorites == 0) ? '0' : article.favorites,
              handler: handleFavorite
            },
            {
              icon: 'fa fa-share fa-2x',
              label: '分享',
              value: '',
              handler: handleShare
            }
          ]" :key="index" class="flex flex-col items-center cursor-pointer hover:text-red-500" @click="item.handler">
            <i :class="item.icon" class="text-2xl"></i>
            <span class="text-sm mt-1">{{ item.label }}</span>
            <span v-if="item.value" class="text-sm text-gray-500">{{ item.value }}</span>
          </div>
        </div>
      </div>

      <!-- 中间内容区域 -->
      <div class="flex-1">
        <!-- 文章内容 -->
        <div class="bg-white rounded-lg p-8 mb-8">
          <h1 class="text-3xl font-bold mb-4">{{ article.title }}</h1>
          <div class="flex items-center text-gray-500 text-sm mb-8">
            <span>{{ article.publishTime }}</span>
            <span class="mx-2">·</span>
            <span class="flex items-center">
              <el-icon class="mr-1">
                <View />
              </el-icon>
              {{ article.readCount }}
            </span>
            <div class="ml-4 flex gap-2">
              <el-tag v-for="tag in article.tags" :key="tag" size="small" effect="plain">
                {{ tag }}
              </el-tag>
            </div>
          </div>

          <div class="article-content prose prose-lg max-w-none" v-html="article.content"></div>
        </div>

        <!-- 评论区 -->
        <div class="bg-white rounded-lg p-8" :key="commentsKey">
          <div class="flex-1">
            <div class="flex items-center justify-between mb-6">
              <h2 class="text-xl font-bold">当前 {{ comments.commentNum }} 条评论</h2>
              <i v-if="sortType === 0" class="fa fa-align-left cursor-pointer" @click="commentSort(1)"> 按时间排序</i>
              <i v-if="sortType === 1" class="fa fa-align-justify cursor-pointer" @click="commentSort(2)"> 按热度排序</i>
              <i v-if="sortType === 2" class="fa fa-align-right cursor-pointer" @click="commentSort(0)"> 按默认排序</i>
            </div>
          </div>

          <!-- 评论输入框 -->
          <div class="mb-8" id="comment-box">
            <el-input v-model="commentContentGlobal" type="textarea" :rows="5" resize="none" placeholder="热评就在眼前..."
              class="mb-4" />
            <div class="text-right">
              <el-button type="primary" @click="submitComment(0, 0, '', commentContentGlobal)">发表评论</el-button>
            </div>
          </div>

          <!-- 评论列表 -->
          <div class="space-y-6">
            <div v-if="comments.commentNum !== 0" v-for="comment in comments.commentList" :key="comment.id"
              class="border-b border-gray-100 pb-6 last:border-none">
              <!-- 主评论 -->
              <div class="flex gap-4">
                <el-avatar :size="40" :src="comment.avatar" class="cursor-pointer"
                  @click="handleUserProfile(comment.userId)" />
                <div class="flex-1">
                  <div class="flex items-center justify-between mb-2">
                    <span class="font-bold cursor-pointer" @click="handleUserProfile(comment.userId)">{{ comment.author
                      }}
                      <el-tag v-if="comment.author === article.author" type="danger" effect="light">作者</el-tag>
                    </span>
                    <span class="text-gray-500 text-sm">
                      {{ comment.time }}
                    </span>
                  </div>
                  <p class="text-gray-700 mb-2">{{ comment.content }}</p>
                  <div class="flex items-center gap-4 text-gray-500 text-sm">
                    <button class="flex items-center gap-1 hover:text-blue-500" @click="likeComment(comment)">
                      <i v-if="comment.supportIf === 0" class="fa fa-thumbs-o-up fa-lg"></i>
                      <i v-else class="fa fa-thumbs-up fa-lg"></i>
                      <span>{{ comment.likes }}</span>
                    </button>
                    <button class="hover:text-blue-500" @click="replyComment(comment.id)">回复</button>
                  </div>
                </div>
              </div>
              <!-- 发表子评论（对一级评论进行回复）用到的的组件 -->
              <div v-if="comment.id === replyCommentId && replyChildCommentId === 0"
                class="ml-14 mt-4 space-y-4 bg-gray-50 p-4 rounded-lg">
                <div class="mb-2">
                  <el-input v-model="childCommentContentGlobal" type="textarea" :rows="3" resize="none"
                    placeholder="我也来说两句..." class="mb-3" />
                  <div class="text-right">
                    <el-button type="primary"
                      @click="submitComment(comment.id, 0, '', childCommentContentGlobal)">回复</el-button>
                  </div>
                </div>
              </div>

              <!-- 回复列表 -->
              <div v-if="comment.replies.length" class="ml-14 mt-4 space-y-4 bg-gray-50 p-4 rounded-lg">
                <div v-for="reply in comment.replies" :key="reply.id" class="flex-col">
                  <div class="flex gap-4 mt-4 mb-6">
                    <el-avatar :size="32" :src="reply.avatar" class="cursor-pointer"
                      @click="handleUserProfile(reply.userId)" />
                    <div class="flex-1">
                      <div class="flex items-center justify-between mb-2">
                        <span class="font-bold cursor-pointer" @click="handleUserProfile(reply.userId)">{{ reply.author
                          }}
                          <el-tag v-if="reply.author === article.author" type="danger" effect="light"
                            size="small">作者</el-tag>
                        </span>
                        <span class="text-gray-500 text-sm">
                          {{ reply.time }}
                        </span>
                      </div>
                      <p class="text-gray-700 mb-2">
                        <el-link v-if="reply.repliedUser" :underline="false" type="primary">@{{ reply.repliedUser
                          }}</el-link>
                        {{ reply.content }}
                      </p>
                      <div class="flex items-center gap-4 text-gray-500 text-sm">
                        <button class="flex items-center gap-1 hover:text-blue-500" @click="likeChildComment(reply)">
                          <i v-if="reply.supportIf === 0" class="fa fa-thumbs-o-up"></i>
                          <i v-else class="fa fa-thumbs-up"></i>
                          <span>{{ reply.likes }}</span>
                        </button>
                        <button class="hover:text-blue-500" @click="replyChildComment(comment.id, reply.id)">回复</button>
                      </div>
                    </div>
                  </div>

                  <!-- 发表子评论（对二级评论进行回复）用到的的组件 -->
                  <div v-if="comment.id === replyCommentId && reply.id === replyChildCommentId" class="flex-col gap-1">
                    <el-divider class="margin-top:5px;margin-bottom:5px;" />
                    <div class="mb-1 ml-10">
                      <el-input v-model="childCommentContentGlobal" type="textarea" :rows="3" resize="none"
                        placeholder="输入回复内容..." class="mb-2" />
                      <div class="text-right">
                        <el-button type="primary"
                          @click="submitComment(comment.id, reply.userId, reply.author, childCommentContentGlobal)">回复</el-button>
                      </div>
                    </div>
                  </div>
                </div>

              </div>
            </div>
            <div v-else="comments.commentNum === 0">
              <el-empty description="暂无评论，快来抢沙发！" />
            </div>
          </div>
        </div>
        <!-- 评论分页器 -->
        <div class="demo-pagination-block">
          <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 50]"
            layout="sizes, prev, pager, next" :total="comments.commentNum" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </div>
      </div>

      <!-- 右侧信息 -->
      <div class="w-72">
        <!-- 作者信息卡片 -->
        <div class="bg-white rounded-lg p-6 mb-6">
          <div class="flex items-center mb-4">
            <el-avatar :size="45" shape="circle" fit="cover" :src="article.authorAvatar" class="cursor-pointer"
              @click="handleUserProfile(article.authorStats.authorId)" />
            <div class="ml-3">
              <div class="font-bold cursor-pointer" @click="handleUserProfile(article.authorStats.authorId)">{{
                article.author }}</div>
              <div class="text-sm text-gray-500">{{ article.authorDesc }}</div>
            </div>
          </div>
          <div class="flex justify-around text-center mb-4">
            <div>
              <div class="font-bold">{{ article.authorStats.articles }}</div>
              <div class="text-sm text-gray-500">文章</div>
            </div>
            <div>
              <div class="font-bold">{{ article.authorStats.followers }}</div>
              <div class="text-sm text-gray-500">粉丝</div>
            </div>
            <div>
              <div class="font-bold">{{ article.authorStats.likes }}</div>
              <div class="text-sm text-gray-500">获赞</div>
            </div>
          </div>
          <el-button v-if="!article.authorStats.followedIf" type="primary" class="w-full"
            @click="handleAuthorFollow(article.authorStats.authorId)">关注</el-button>
          <el-button v-else type="default" class="w-full"
            @click="handleAuthorFollow(article.authorStats.authorId)">已关注</el-button>
        </div>

        <!-- 相关推荐 -->
        <div class="bg-white rounded-lg p-6">
          <h3 class="font-bold mb-4">相关推荐</h3>
          <div class="space-y-4">
            <div v-for="item in relatedArticles" :key="item.id" class="cursor-pointer hover:bg-gray-50 p-2 rounded">
              <div class="text-base font-bold mb-2 line-clamp-2 hover:text-blue-500">
                {{ item.title }}
              </div>
              <div class="text-gray-500 text-sm flex items-center gap-1">
                <el-icon>
                  <View />
                </el-icon>
                {{ item.readCount }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
// .article-content {
//   :deep(img) {
//     @apply my-4 rounded-lg w-full;
//   }

//   :deep(h2) {
//     @apply text-2xl font-bold my-4;
//   }

//   :deep(p) {
//     @apply my-4 leading-relaxed text-gray-700;
//   }
// }

// 分页组件样式
.demo-pagination-block {
  text-align: center;
  margin-top: 20px;
}

.demo-pagination-block+.demo-pagination-block {
  margin-top: 10px;
}

.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
</style>
